<?php

namespace app\api\controller\mycurrency;

use addons\mycurrency\library\Common;
use app\common\controller\Api;
use app\common\library\device\cabinet\Analysis;
use app\common\library\device\cabinet\Control;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\billiard\StoreGoods;
use app\common\model\mycurrency\Device;
use app\common\model\mycurrency\DeviceInstruction;
use app\common\model\mycurrency\DeviceLattice;
use app\common\model\mycurrency\LeaseConfig;
use app\common\model\mycurrency\LeaseOrder;
use app\common\model\mycurrency\LeaseOrderDevice;
use app\common\model\mycurrency\LeaseOrderPay;
use app\common\model\mycurrency\LeaseStrategy;
use app\common\model\mycurrency\LeaseStrategyPackage;
use app\common\model\mycurrency\OperateDistributionMoneylog;
use app\common\model\mycurrency\OperateDistributionUser;
use app\common\model\mycurrency\UserMoneyLog;
use app\common\model\WechatChapterOrder;
use fast\Random;
use think\Config;
use think\Exception;
use think\Validate;
use think\Db;

/**
 * 租赁接口
 */
class Lease extends Api
{
    protected $noNeedLogin = ['leaseConfig'];
    protected $noNeedRight = '*';
    protected $agent = null;


    public function _initialize()
    {
        parent::_initialize();
    }




    /**
     * 获取配置
     */
    public function leaseConfig(){
        $data = LeaseConfig::get(1);
        $this->success('',$data);
    }

    /**
     * 获取租赁信息详情
    */
    public function leaseInfo(){
        $param = $this->request->param();
        $rule = [
            //['device_number', 'require', '设编号不能为空'],
            //['store_goods_id', 'require', '门店产品id不能为空'],
            ['device_lattice_id','require', '设备柜门id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $lattice = DeviceLattice::get($param['device_lattice_id']);
        $param['device_number'] = Device::where(['id' => $lattice->device_id])->value('number');
        $param['store_goods_id'] = $lattice->store_goods_id;
        try {
            //查询台球柜信息，并验证是否可用
            $device = Device::canorcantLease(null,$param['device_number']);
            $store_goods = StoreGoods::with(['goods'])->where(['id' => $param['store_goods_id'],'deletetime' => null])->find();
            if(!$store_goods){
                $this->error('门店产品不存在');
            }
            //收费策略相关信息
            $strategy_id = $store_goods['lease_strategy_id'];
            $strategy = LeaseStrategy::where(['id' => $strategy_id,'deletetime' => null])->find();
            if(!$strategy){
                throw new Exception('租赁策略不存在');
            }
            $charge_standard = '';//收费标准
            $charge_package = [];//套餐信息
            if($strategy['types'] == LeaseStrategy::TYPES_SHICHANG){//策略类型:1=按时长计费
                $charge_standard = "{$strategy['unit_price']}元/{$strategy['duration']}分钟";
            }elseif ($strategy['types'] == LeaseStrategy::TYPES_CISHU){//策略类型:2=按次数计费
                $charge_standard = "{$strategy['unit_price']}元/次";
            }elseif ($strategy['types'] == LeaseStrategy::TYPES_TAOCAN){//策略类型:3=按套餐计费
                $charge_standard = "选择租赁时长，超时归还{$strategy['overtime_money']}元/{$strategy['overtime_company']}分钟";
                $charge_package = LeaseStrategyPackage::where([
                    'strategy_id' => $strategy->id,
                    'status' => LeaseStrategyPackage::STATUS_ZHENGCHENG,
                    'deletetime' => null
                ])->field('id,title,duration,money')->select();
                foreach($charge_package as $k => $v){
                    switch ($strategy['package_types']) {
                        case LeaseStrategy::PACKAGE_TYPES_FENZHONG:
                            $charge_package[$k]['duration'] .= '分钟';
                            break;
                        case LeaseStrategy::PACKAGE_TYPES_XIAOSHI:
                            $charge_package[$k]['duration'] .= '小时';
                            break;
                        case LeaseStrategy::PACKAGE_TYPES_TIAN:
                            $charge_package[$k]['duration'] .= '天';
                            break;
                        default:
                            break;
                    }
                }
            }
        } catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $data = [
            'goods_title' => $store_goods['goods']['title'],
            'goods_abbreviation_image' => Common::GetHost() . $store_goods['goods']['abbreviation_image'],
            'charge_standard' => $charge_standard,
            'advance_fee' => $store_goods['advance_fee'],
            'rule_rxplain' => LeaseConfig::where(['id' => 1])->value('rule_rxplain'),
            'overtime_money' => $strategy['overtime_money'],
            'overtime_company' => $strategy['overtime_company'],
            'unit_price' => $strategy['unit_price'],
            'duration' => $strategy['duration']
        ];
        $this->success('',$data);
    }

    /**
     * 租赁订单下单
     */
    public function leasePlaceanorder(){
        $param = $this->request->param();
        $rule = [
            //['device_number', 'require', '设编号不能为空'],
            //['store_goods_id', 'require', '门店产品id不能为空'],
            ['device_lattice_id','require', '设备柜门id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        //租赁方式
        if (!array_key_exists('lease_way',$param)){
            $param['lease_way'] = 0;//租赁方式:0 按照系统设置 1 免押 2 缴纳预付金 3 先付后用 4 先用后付
        }

        //终端
        if (!array_key_exists('terminal',$param)){
            $param['terminal'] = 'wechat';//终端 ： wechat 微信（默认） ， alipay 支付宝
        }

        $lattice = DeviceLattice::get($param['device_lattice_id']);
        $param['device_number'] = Device::where(['id' => $lattice->device_id])->value('number');
        $param['store_goods_id'] = $lattice->store_goods_id;
        //验证用户是否有租赁中订单
        $user_order = LeaseOrder::where([
            'user_id' => $this->auth->id,
            //'use_status' => LeaseOrder::USE_STATUS_ZHIFUHOUFU,
            'use_status' => [
                'in',[
                    LeaseOrder::USE_STATUS_MIANYA,
                    LeaseOrder::USE_STATUS_YAJIN,
                    LeaseOrder::USE_STATUS_ZHIFUXIANFU,
                    LeaseOrder::USE_STATUS_JINXINGZHONG,
                    LeaseOrder::USE_STATUS_ZHIFUHOUFU
                ]
            ],
            'deletetime' => null
        ])->find();
        if ($user_order){
            $this->error('有未结束的订单，不能重复租赁');
        }
        Db::startTrans();
        try {
            //查询台球柜信息，并验证是否可用
            $device = Device::canorcantLease(null,$param['device_number']);
            list($order_id,$advance_fee) = LeaseOrder::orderAdd($device,$this->auth->id,$param['store_goods_id'],null,$param['device_lattice_id'],$param['lease_way']);
            /**
             * 后续操作
             * 免押 ： 如果使用免押 是不需要缴纳押金 及先付款的
             * 缴纳押金 ： 如果需要缴纳押金，缴纳押金以后可以直接租赁，是不需要先付租赁费用的
             * 先付后用 ： 如果不是用免押也不需要缴纳押金，用户可以先支付费用 或者 后支付费用
             */
            $data = [];
            $order = LeaseOrder::get($order_id);
            $operate = null;//后续操作 1 调起免押 2 缴纳押金 3 支付租赁费用 4 打开设备
            //使用免押 - 调起免押，免押成功后打开设备
            if ($order->use_status == LeaseOrder::USE_STATUS_MIANYA){
                $operate = 1;
                //生成免押订单并获取申请参数
                list($chapter_order_id,$credit) = WechatChapterOrder::generate($order->id,$order->user_id,$order->charge_description,$param['terminal'],[
                    'lease_order_id' => $order->id,
                ]);
                $order->credit_id = $chapter_order_id;
                $order->save();
                $data['credit'] = $credit;//调起免押需要的参数
            }
            //需要缴纳押金 - 缴纳押金，支付成功后打开设备
            elseif ($order->use_status == LeaseOrder::USE_STATUS_YAJIN){
                $operate = 2;
                //创建押金支付记录
                $deposit = \app\common\model\mycurrency\LeaseDeposit::depositAdd($order->user_id,$order->id,$advance_fee);
                $data['deposit'] = $deposit;
                $order->deposit_id = $deposit->id;
                $order->save();
            }
            //先付后用 - 支付租赁费用，支付成功后打开设备
            elseif ($order->use_status == LeaseOrder::USE_STATUS_ZHIFUXIANFU){
                $operate = 3;
                //创建租赁费用支付记录
                $pay = LeaseOrderPay::payAdd($order->id,LeaseOrderPay::PAY_OPPORTUNITY_SHIYONGQIAN);
                $data['pay'] = $pay;
            }
            //先用后付款 - 打开设备
            elseif ($order->use_status == LeaseOrder::USE_STATUS_JINXINGZHONG){
                $operate = 4;
                //开始租赁设备
                LeaseOrder::orderStartRenting($order->id);
            }
            $data['operate'] = $operate;
            $data['order'] = $order;

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        $this->success('订单生成成功',$data);
    }

    /**
     * 归还设备 - 发送开门指令
    */
    public function leaseReturn(){
        $param = $this->request->param();
        $rule = [
            ['lease_order_id', 'require', '订单id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        trace(["5========================处理lease_order_id报错问题_leaseReturn==============================" => $param],'error');
        $lease_order = LeaseOrder::where(['id' => $param['lease_order_id'],'deletetime' => null])->find();
        if(!$lease_order){
            $this->error('订单不存在');
        }
        if($lease_order->use_status != LeaseOrder::USE_STATUS_JINXINGZHONG){
            $this->error('订单非使用中状态');
        }

        $lease_order_device = LeaseOrderDevice::where(['lease_order_id' => $lease_order->id,'deletetime' => null,'status' => [
            'in',[
                LeaseOrderDevice::STATUS_SHIYONGZHONG,
                LeaseOrderDevice::STATUS_GUIHUANZHONG,
            ]
        ]])->order('id desc')->find();
        if (!$lease_order_device){
            $this->error('无设备使用记录');
        }
        if($lease_order_device->status == LeaseOrderDevice::STATUS_GUIHUANZHONG){
            $this->error('归还中请勿重复操作');
        }
        Db::startTrans();
        try {
            //调用设备模型控制设备指令 - 下发指令打开设备
            $device_lattice = DeviceLattice::get($lease_order_device->device_lattice_id);
            $data = "49,{$device_lattice['number']}&1";//[33,$device_lattice->number,1];
            Control::sending($lease_order_device->device_id,Analysis::CODE_KAIMEN,$data,[
                'device_lattice_id' => $device_lattice->id,//柜门id
                'control_type' => DeviceInstruction::CONTROL_TYPE_GUIHUANKAIMEN,//控制类型 = 用户归还开门
                'lease_order_device_id' => $lease_order_device->id,//用户租赁订单设备使用记录表id
            ]);
            //修改状态
            $lease_order_device->status = LeaseOrderDevice::STATUS_GUIHUANZHONG;//修改设备使用记录为归还中
            $lease_order_device->return_open_progress = LeaseOrderDevice::RETURN_OPEN_PROGRESS_KAIMENZHONG;//归还开门进度修改为开门中
            $lease_order_device->save();
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('操作开门成功');
    }

    /**
     * 租赁订单支付 = 余额支付
     * 说明 ： 租赁订单 可能先付后用 也可能先用后付款
     */
    public function leasePay(){
        $param = $this->request->param();
        $rule = [
            ['lease_order_pay_id', 'require', '支付记录id不能为空'],
        ];
        $check = $this->validate($param, $rule);
        if ($check !== true) {
            $this->error($check);
        }
        $order_pay = LeaseOrderPay::get($param['lease_order_pay_id']);
        if(!$order_pay){
            $this->error('支付记录不存在');
        }
        if($order_pay['pay_status'] != LeaseOrderPay::PAY_STATUS__DAIZHIFU){
            $this->error('非待支付状态');
        }
        $user = \app\common\model\User::get($this->auth->id);
//        if($user->money < $order_pay['money']){
//            $this->error('余额不足');
//        }
        $distribution_user = OperateDistributionUser::where(['user_id' => $user->id])->find();
        if($distribution_user->money < $order_pay['money']){
            $this->error('余额不足');
        }
        Db::startTrans();
        try {
            //扣除用户余额
//            UserMoneyLog::moneyChange($user->id,$order_pay['money'],UserMoneyLog::TYPE_ZULINFEIYONGZHIFU,[
//                'memo' => '支付租赁订单租赁费用',
//                'lease_order_pay_id' => $order_pay->id,
//            ]);
            //扣除用户分销余额
            OperateDistributionMoneylog::moneyChange($distribution_user->id,$order_pay['money'],OperateDistributionMoneylog::TYPE_DINGDANZHIFU,[
                'memo' => '支付租赁订单租赁费用',
                'lease_order_pay_id' => $order_pay->id,
            ]);
            //处理租赁费用支付成功后逻辑
            LeaseOrderPay::paySuccess($order_pay->id,LeaseOrderPay::PAY_TYPE_YUE);
            Db::commit();
        } catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('支付成功');
    }


    /**
     * 租赁订单列表
     */
    public function leaseList(){
        $params = $this->request->param();
        $rule = [
            ['page', 'require', '页码不能为空'],
            ['pageSize', 'require', '每页查询条数不能为空'],
            ['status',"require|in:0,1,2,3", '查询类型不能为空|查询类型错误'],//查询类型：0=全部，1=租赁中，2=待支付，3=已完成
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'user_id' => $this->auth->id,
            'deletetime' => null,
        ];
        switch ($params['status']) {
            case 1:
                $where['use_status'] = LeaseOrder::USE_STATUS_JINXINGZHONG;
                break;
            case 2:
                $where['use_status'] = ['in',[
                    LeaseOrder::USE_STATUS_MIANYA,
                    LeaseOrder::USE_STATUS_YAJIN,
                    LeaseOrder::USE_STATUS_ZHIFUXIANFU,
                    LeaseOrder::USE_STATUS_ZHIFUHOUFU,
                ]];
                break;
            case 3:
                $where['use_status'] = LeaseOrder::USE_STATUS_YIWANCHENG;
                break;
            default:
                $where['use_status'] = ['<>',LeaseOrder::USE_STATUS_YIQUXIAO];
                break;
        }

        $list = LeaseOrder::with([
                'deposit',//免押记录
                'pendingpayment' => function($query){//待支付的租赁费用
                    $query->where([
                        'pay_status' => LeaseOrderPay::PAY_STATUS__DAIZHIFU,
                        'deletetime' => null,
                    ]);
                    $query->order('id desc');
                },
                'rentingingrogressdevice' => function($query){//使用中的设备
                    $query->order('id desc');
                },
            ])
            ->where($where)
            ->limit(($params['page'] - 1) * $params['pageSize'], $params['pageSize'])
            ->order('id desc')
            ->field('*')
            ->select();
        foreach($list as $k => $v){
            $list[$k] = LeaseOrder::getUseStatusText($v);//订单状态
            $list[$k]['operate'] = LeaseOrder::operationJurisdiction($v);//操作权限
            $list[$k]['use_duration'] = LeaseOrder::useDuration(strtotime($v['lease_time']),strtotime($v['return_time']),strtotime($v['createtime']));//使用时长
        }
        $num = LeaseOrder::where($where)->count();
        if ($num > $params['page'] * $params['pageSize']) {
            $nextpage = true;
        } else {
            $nextpage = false;
        }
        $this->success('获取成功', ['list' => $list, 'nextpage' => $nextpage]);
    }


    /**
     * 租赁订单详情
     */
    public function leaseOrderInfo(){
        $params = $this->request->param();
        $rule = [
            ['order_id', 'require', '订单id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'id' => $params['order_id'],
            'user_id' => $this->auth->id,
            'deletetime' => null,
        ];

        $data = LeaseOrder::with([
            'deposit',//免押记录
            'pendingpayment' => function($query){//待支付的租赁费用
                $query->where([
                    'pay_status' => LeaseOrderPay::PAY_STATUS__DAIZHIFU,
                    'deletetime' => null,
                ]);
                $query->order('id desc');
            },
            'rentingingrogressdevice' => function($query){//使用中的设备
                $query->order('id desc');
                $query->with(['device' => function($query){
                    $query->field('id,title,is_infra_red');
                },'lattice' => function($query){
                    $query->field('id,number');
                }]);
            },
            'store' => function($query){//待支付的租赁费用
                $query->find('id,store_name,phone,address');
            }
        ])
            ->where($where)
            ->field('*')
            ->find();
        $data = LeaseOrder::getUseStatusText($data);
        $data['operate'] = LeaseOrder::operationJurisdiction($data);
        $data['device'] = [
            'title' => $data['rentingingrogressdevice']['device']['title'],
            'number' => $data['rentingingrogressdevice']['lattice']['number'],
            'is_infra_red' => $data['rentingingrogressdevice']['device']['is_infra_red'],
            'order_device_status' => $data['rentingingrogressdevice']['status'],
        ];
        unset($data['rentingingrogressdevice']['device']);
        unset($data['rentingingrogressdevice']['lattice']);
        $data['use_duration'] = LeaseOrder::useDuration(strtotime($data['lease_time']),strtotime($data['return_time']),strtotime($data['createtime']));//使用时长

        //是否继续轮训 1 继续轮训 2 停止轮训

        $is_continue_query = 2;
        if ($data['device']['is_infra_red'] == Device::IS_INFRA_RED_YOU){//归还需要检测红外
            if(
                $data['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_WEIJIANCE || //归还检测-门状态检测:1=未检测
                $data['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_JIANCEZHONG || //归还检测-门状态检测:2=检测中

                $data['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_WEIJIANCE || //归还检测-sd卡检测状态:1=未检测
                $data['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_JIANCEZHONG || //归还检测-sd卡检测状态:2=检测中

                $data['rentingingrogressdevice']['detection_infrared_status'] == LeaseOrderDevice::DETECTION_INFRARED_STATUS_WEIJIANCE || //归还检测-红外检测状态:1=未检测
                $data['rentingingrogressdevice']['detection_infrared_status'] == LeaseOrderDevice::DETECTION_INFRARED_STATUS_JIANCEZHONG //归还检测-红外检测状态:2=检测中
            ){//门开关 nfc卡 红外遮挡 没有在检测中的了 就停止轮训
                $is_continue_query = 1;
            }
        }elseif ($data['device']['is_infra_red'] == Device::IS_INFRA_RED_WU){//归还不需要检测红外
            if(
                $data['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_WEIJIANCE || //归还检测-门状态检测:1=未检测
                $data['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_JIANCEZHONG || //归还检测-门状态检测:2=检测中

                $data['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_WEIJIANCE || //归还检测-sd卡检测状态:1=未检测
                $data['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_JIANCEZHONG //归还检测-sd卡检测状态:2=检测中
            ){//门开关 nfc卡 红外遮挡 没有在检测中的了 就停止轮训
                $is_continue_query = 1;
            }
        }


        //是否显示开门按钮1 不显示 2 显示
        $is_door = 1;
        if(
            $data['rentingingrogressdevice']['status'] == LeaseOrderDevice::STATUS_JIANCEZHONG &&//5=检测中
            $data['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_YITONGGUO && //检测到已关门
            (
                $data['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_WUKA ||//未检测到sd卡
                $data['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_KACUOWU || //检测到错误的sd卡

                $data['rentingingrogressdevice']['detection_infrared_status'] == LeaseOrderDevice::DETECTION_INFRARED_STATUS_WEIZHEDANG //未检测到红外遮挡
            )
        ){
            $is_door = 2;
        }

        $data['is_continue_query'] = $is_continue_query;
        $data['is_door'] = $is_door;

        //预付金是否足够支付租赁费用
        $is_paylater = 1;//是否需要扣完预付金后还需要在支付租赁费用
        $paymen_required = $data['paymen_required'];//实际总需要支付金额(租赁费用 + 超市归还费用 - 各种优惠)
        if($data['credit_id'] != null){//预付金支付方式 免押
            if ($paymen_required > 99){//扣完预付金后还需要在支付费用
                $is_paylater = 2;
            }
        }elseif ($data['deposit_id'] != null){//预付金支付方式 押金
            $deposit = \app\common\model\mycurrency\LeaseDeposit::where(['id' => $data['deposit_id']])->find();
            if ($paymen_required > $deposit['amount']){//扣完预付金后还需要在支付费用
                $is_paylater = 2;
            }
        }
        $data['is_paylater'] = $is_paylater;
        $this->success('获取成功', $data);
    }

    /**
     * 归还中出现异常 用户再次开门
     * 场景：用户归还后 系统检测到 红外遮挡异常 或者 nfc卡异常 用户可以再次开门检查
     */
    public function returnAgainDoor(){
        $params = $this->request->param();
        $rule = [
            ['order_id', 'require', '订单id不能为空'],
        ];
        $check = $this->validate($params, $rule);
        if ($check !== true) {
            $this->error($check);
        }

        $where = [
            'id' => $params['order_id'],
            'user_id' => $this->auth->id,
            'deletetime' => null,
        ];

        $lease_order = LeaseOrder::with(
            [
                'rentingingrogressdevice' => function($query){//使用中的设备
                    $query->order('id desc');
                    $query->with(['device' => function($query){
                        $query->field('id,title');
                    },'lattice' => function($query){
                        $query->field('id,number');
                    }]);
                }
            ]
        )
            ->where($where)
            ->field('*')
            ->find();
        if (!$lease_order){
            $this->error('订单不存在');
        }

        if($lease_order['rentingingrogressdevice']['status'] != LeaseOrderDevice::STATUS_JIANCEZHONG){
            $this->error('订单非检测中');
        }

        //门检测状态判断 只有检测到门已经关闭 才可以操作开门
        if ($lease_order['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_WEIGUANMEN){//归还检测-门状态检测:-1=检测到未关门
            $this->error('检测到门未关闭');
        }
        if ($lease_order['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_WEIJIANCE){//归还检测-门状态检测:1=未检测
            $this->error('门状态未检测');
        }
        if ($lease_order['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_JIANCEZHONG){//归还检测-门状态检测:2=检测中
            $this->error('门状态检测中');
        }

        //NFC卡检测状态判断 只有 未检测到卡id 及卡id错误 才可以操作开门
        if ($lease_order['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_WEIJIANCE){//归还检测-sd卡检测状态:1=未检测
            $this->error('NFC卡未检测');
        }
        if ($lease_order['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_JIANCEZHONG){//归还检测-sd卡检测状态:2=检测中
            $this->error('NFC卡检测中');
        }

        //红外遮挡检测状态判断 只有未检测到遮挡才可以开门
        if ($lease_order['rentingingrogressdevice']['detection_infrared_status'] == LeaseOrderDevice::DETECTION_INFRARED_STATUS_WEIJIANCE){//归还检测-红外检测状态:1=未检测
            $this->error('红外遮挡没有检测');
        }
        if ($lease_order['rentingingrogressdevice']['detection_infrared_status'] == LeaseOrderDevice::DETECTION_INFRARED_STATUS_JIANCEZHONG){//归还检测-红外检测状态:2=检测中
            $this->error('红外遮挡检测中');
        }

        //判断是否全部检测通过 如果全部检测通过就不需要再开门了
        if(
            $lease_order['rentingingrogressdevice']['detection_door_status'] == LeaseOrderDevice::DETECTION_DOOR_STATUS_YITONGGUO &&
            $lease_order['rentingingrogressdevice']['detection_block_status'] == LeaseOrderDevice::DETECTION_BLOCK_STATUS_YITONGGUO &&
            $lease_order['rentingingrogressdevice']['detection_infrared_status'] == LeaseOrderDevice::DETECTION_INFRARED_STATUS_YITONGGUO
        ){
            $this->error('检测都已经通过无需开门');
        }
        Db::startTrans();
        try {
            //修改状态
            LeaseOrderDevice::where(['id' => $lease_order['rentingingrogressdevice']['id']])->update([
                'status' => LeaseOrderDevice::STATUS_GUIHUANZHONG,////修改设备使用记录为归还中
                'detection_door_status' => LeaseOrderDevice::DETECTION_DOOR_STATUS_WEIJIANCE,//归还检测-门状态检测:1=未检测
                'detection_block_status' => LeaseOrderDevice::DETECTION_BLOCK_STATUS_WEIJIANCE,//归还检测-sd卡检测状态:1=未检测
                'detection_infrared_status' => LeaseOrderDevice::DETECTION_INFRARED_STATUS_WEIJIANCE,//归还检测-红外检测状态:1=未检测
                'return_open_progress' => LeaseOrderDevice::RETURN_OPEN_PROGRESS_KAIMENZHONG,//归还开门进度修改为开门中
            ]);

            //调用设备模型控制设备指令 - 下发指令打开设备
            $device = Device::get($lease_order['rentingingrogressdevice']['device_id']);
            $device_lattice = DeviceLattice::get($lease_order['rentingingrogressdevice']['device_lattice_id']);
            $data = "33,{$device_lattice['number']}&1";
            Control::sending($device->id,Analysis::CODE_KAIMEN,$data,[
                'device_lattice_id' => $device_lattice->id,//柜门id
                'control_type' => DeviceInstruction::CONTROL_TYPE_GUIHUANKAIMEN,//控制类型 = 用户归还开门
                'lease_order_device_id' => $lease_order['rentingingrogressdevice']['id'],//用户租赁订单设备使用记录表id
            ]);
            Db::commit();
        } catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('');
    }



    public function text(){
        $params = $this->request->param();
        if ($params['type'] == 1 || $params['type'] == 2){
            //租赁订单 开锁结果通知
            Db::startTrans();
            try {
                LeaseOrderDevice::deviceOpenResult($params['device_lattice_id'],$params['type']);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }elseif ($params['type'] == 3){
            //订单归还
            Db::startTrans();
            try {
                LeaseOrderDevice::deviceReturn($params['device_lattice_id']);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }elseif ($params['type'] == 20){
            //订单分佣
            Db::startTrans();
            try {
                LeaseOrder::orderDivideinto(12);
                Db::commit();
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
        }



    }

    /**
     * 租赁订单下单前查询是否有租赁中的订单
     */
    public function leaseInprogressOrder(){
        $param = $this->request->param();
//        $rule = [
//            ['device_number','require', '设备编号不能为空'],
//        ];
//        $check = $this->validate($param, $rule);
//        if ($check !== true) {
//            $this->error($check);
//        }
        $is_inprogress = 1;//是否有进行中订单 1 无进行中订单 2 有进行中订单
        $order_id = null;//进行中订单id
        if ($param['device_number'] != ''){
            $device = Device::where(['number' => $param['device_number'],'deletetime' => null])->find();
            if (!$device){
                $this->error('设备不存在');
            }
            $order_device = LeaseOrderDevice::where([
                'user_id' => $this->auth->id,
                'device_id' => $device->id,
                'status' => ['<>',LeaseOrderDevice::STATUS_QUXIAO],
                'deletetime' => null,
            ])->order('id desc')->find();
            if($order_device){
                if ($order_device->status != LeaseOrderDevice::STATUS_YIGUIHUAN){//如果状态不等于已完成 说明设备还在使用中
                    $is_inprogress = 2;
                    trace(["6========================处理lease_order_id报错问题_leaseInprogressOrder==============================" => $order_device],'error');
                    $order_id = $order_device->lease_order_id;
                }else{//如果状态等于已完成 查询订单是否支付了
                    trace(["7========================处理lease_order_id报错问题_leaseInprogressOrder 2==============================" => $order_device],'error');
                    $order = LeaseOrder::where(['id' => $order_device->lease_order_id])->find();
                    if ($order && $order->use_status != LeaseOrder::USE_STATUS_YIWANCHENG){
                        $is_inprogress = 2;
                        $order_id = $order->id;
                    }
                }
            }
        }else{
            $order = LeaseOrder::where([
                'user_id' => $this->auth->id,
                'use_status' => ['not in',[
                    LeaseOrder::USE_STATUS_YIQUXIAO,
                    LeaseOrder::USE_STATUS_YIWANCHENG,
                ]],
                'deletetime' => null,
            ])->find();
            if ($order){
                $is_inprogress = 2;
                $order_id = $order->id;
            }
        }

        $this->success('加载成功',[
            'is_inprogress' => $is_inprogress,
            'order_id' => $order_id,
        ]);
    }
}
